package src.main.java.org.thread.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private double money;
    private String cardId;

    private final Lock lk = new ReentrantLock(); //创建锁对象,加final防止替换

    public Account() {
    }
    public static void test(){
        synchronized (Account.class){ //如果是静态方法可以用类名.class文件作为锁

        }
    }
//    public synchronized void drawMoney(double money){ //同步方法
    public void drawMoney(double money){
        //先搞清楚谁取钱
        String name = Thread.currentThread().getName();
        lk.lock();//使用锁对象加锁
        //判断余额是否足够
//        synchronized (this) {//上锁,this代表共享资源，同步代码块
        try {
            if(this.money>=money){
                System.out.println(name+"取钱成功！");
                this.money -= money;
                System.out.println(name+"来取钱，剩余"+this.money);
            }else{
                System.out.println(name+"来取钱，余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();//解锁
        }

//        }
    }

    public Account(double money, String cardId) {
        this.money = money;
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }
}
